package ipmss.security;

import ipmss.services.common.UserContext;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;

import javax.inject.Inject;
import javax.inject.Named;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.web.context.request.RequestContextHolder;

// TODO: Auto-generated Javadoc
/**
 * The Class MyAuthenticationProvider.
 *
 * @author Michał Czarnik
 */
@Named
public class MyAuthenticationProvider implements AuthenticationProvider
{
    
    /** The user context. */
    @Inject
    private UserContext userContext;

    /** The Constant AUTHORITIES. */
    static final ArrayList<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>();

    static
    {
	AUTHORITIES.add(new GrantedAuthorityImpl("ROLE_USER"));
	AUTHORITIES.add(new GrantedAuthorityImpl("ROLE_MODERATOR"));
	AUTHORITIES.add(new GrantedAuthorityImpl("ROLE_ADMIN"));

    }

    /* (non-Javadoc)
     * @see org.springframework.security.authentication.AuthenticationProvider#authenticate(org.springframework.security.core.Authentication)
     */
    public Authentication authenticate(Authentication arg)
	    throws AuthenticationException
    {
	//Collection<GrantedAuthority> auth = arg0.getAuthorities();
	ArrayList<GrantedAuthority> auth = new ArrayList<GrantedAuthority>();
	for( Field f :Authorities.class.getDeclaredFields())
	{
	    String s = "";
	    try
	    {
		s = (String) f.get(null);
	    } catch (IllegalArgumentException e)
	    {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    } catch (IllegalAccessException e)
	    {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	    auth.add(new GrantedAuthorityImpl(s) );
	}
	auth.add(AUTHORITIES.get(0));
	auth.add(AUTHORITIES.get(1));
	//arg.getAuthorities().addAll((auth));
	UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
		arg.getName(), arg.getCredentials(), auth);
	authToken.setDetails(arg.getDetails());
	//RequestContextHolder.currentRequestAttributes().setAttribute("AAA", new String("sdfsd"), 5);
//	arg0.getPrincipal()
	
	// no god: throws  BadCredentialsException
	userContext.init(arg.getName());
	return authToken;
    }

    /* (non-Javadoc)
     * @see org.springframework.security.authentication.AuthenticationProvider#supports(java.lang.Class)
     */
    public boolean supports(Class<? extends Object> arg0)
    {
	// TODO Auto-generated method stub
	return true;
    }

}
